package com.milk.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milk.system.common.util.DateUtils;
import com.milk.system.converter.OrdersConverter;
import com.milk.system.mapper.MerchantsMapper;
import com.milk.system.mapper.OrdersMapper;
import com.milk.system.model.entity.Merchants;
import com.milk.system.model.entity.Orders;
import com.milk.system.model.form.OrdersForm;
import com.milk.system.model.query.OrdersPageQuery;
import com.milk.system.model.vo.OrdersPageVO;
import com.milk.system.service.MerchantsService;
import com.milk.system.service.OrdersService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 订单信息表服务实现类
 *
 * @author milk
 * @since 2024-05-04
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    private final OrdersConverter ordersConverter;

    private final MerchantsMapper merchantsMapper;

    private final MerchantsService merchantsService;

    /**
     * 获取订单信息表分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<OrdersPageVO>} 订单信息表分页列表
     */
    @Override
    public IPage<OrdersPageVO> listPagedOrderss(OrdersPageQuery queryParams) {

        //根据商家名称查出商家信息
        Merchants merchantsInfo = null;
        if (queryParams.getMerchantName() != null){
             merchantsInfo = merchantsMapper.getMerchantsName(queryParams.getMerchantName());
        }
        // 参数构建
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 格式化为数据库日期格式，避免日期比较使用格式化函数导致索引失效
        DateUtils.toDatabaseFormat(queryParams, "startTime", "endTime");
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(queryParams.getCustomerName()), Orders::getCustomerName, queryParams.getCustomerName());
        if (null != merchantsInfo){
            wrapper.eq(Orders::getMerchantId, merchantsInfo.getId());
        }
        wrapper.eq(queryParams.getOrderStatus() != null, Orders::getOrderStatus, queryParams.getOrderStatus());
        Page<Orders> boPage = this.page(new Page<>(pageNum, pageSize), wrapper);
        log.info("订单信息表分页列表boPage：{}", boPage.getRecords());
        List<OrdersPageVO> payments = new ArrayList<>();
        boPage.getRecords().forEach(bo -> {
            // 根据商家id查出商家名称
            Merchants merchants = merchantsMapper.getMerchantsId(bo.getMerchantId());
            OrdersPageVO vo = OrdersPageVO.builder()
                    .id(bo.getId())
                    .orderDate(bo.getOrderDate())
                    .customerName(bo.getCustomerName())
                    .customerEmail(bo.getCustomerEmail())
                    .merchantName(merchants == null ? null : merchants.getMerchantName())
                    .createdTime(bo.getCreatedTime())
                    .updatedTime(bo.getUpdatedTime())
                    .orderStatus(bo.getOrderStatus())
                    .totalAmount(bo.getTotalAmount())
                    .build();
            payments.add(vo);
        });
        IPage<OrdersPageVO> result = new Page<>(pageNum, pageSize);
        result.setCurrent(boPage.getCurrent());
        result.setSize(boPage.getSize());
        result.setTotal(boPage.getTotal());
        result.setRecords(payments);
        result.setPages(boPage.getPages());
        // 实体转换
        return result;
    }

    @Override
    public boolean saveProducts(OrdersForm formData) {
        Merchants merchants = merchantsService.getById(formData.getMerchantId());
        Assert.isTrue(merchants != null, "商家不存在");
        Assert.isFalse(merchants.getDeleted(), "商家已被删除");
        Orders orders = new Orders();
        BeanUtils.copyProperties(formData,orders);
        orders.setCreatedTime(LocalDateTime.now());
        orders.setOrderDate(LocalDateTime.now());
        orders.setDeleted(false);
        return this.save(orders);
    }

    @Override
    public boolean updateProducts(Long id, OrdersForm formData) {
        Merchants merchants = merchantsService.getById(formData.getMerchantId());
        Assert.isTrue(merchants != null, "商家不存在");
        Assert.isFalse(merchants.getDeleted(), "商家已被删除");
        Orders byId = this.getById(id);
        BeanUtils.copyProperties(formData,byId);



        return this.updateById(byId);
    }

    @Override
    public boolean deleteProductss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的订单信息表数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }


    @Override
    public OrdersForm getMerchantsFormData(Long id) {
        OrdersForm ordersForm = new OrdersForm();
        BeanUtils.copyProperties(this.getById(id),ordersForm);
        return  ordersForm;
    }
}
